package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 对报表进行操作
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {
    /**
     * 会员统计的折线图数据
     * @return
     */
@Autowired
private MemberService memberService;
@Autowired
private SetMealService setMealService;

    /**
     * 折线图,统计会员数量变化
     * @return
     */
   @GetMapping("/getMemberReport")
   public Result getMemberReport() {
       Map<String,Object> map = new HashMap<>();
       List<String> months = new ArrayList();
       //获得日历对象模拟时间就是当前时间
       Calendar calendar = Calendar.getInstance();
       //计算过去一年的12个月
       calendar.add(Calendar.MONTH,-12);
       for (int i = 0; i < 12; i++) {
           calendar.add(Calendar.MONTH,1);
           Date date = calendar.getTime();
           months.add(new SimpleDateFormat("yyyy.MM").format(date));
       }
       map.put("months",months);
       List<Integer> memberCount = memberService.findMemberCountByMonths(months);
       //查数据库
       map.put("memberCount",memberCount);
      return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
   }


   @RequestMapping("/getSetmealReport")
   public Result getSetmealReport() {
//       使用模拟数据测试
//       List<String> setmealName = new ArrayList();
//       setmealName.add("体检套餐");
//       setmealName.add("孕前检查套餐");
       try {
           List<Map<String,Object>> setmealCount = setMealService.findSetmealCount();
           Map<String,Object> data = new HashMap<>();
           List<String> setmealName = new ArrayList();
           for (Map<String, Object> map : setmealCount) {
               String name =(String) map.get("name");   //套餐名称
               setmealName.add(name);
           }
           data.put("setmealName",setmealName);
           data.put("setmealCount",setmealCount);
           return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
       } catch (Exception e) {
           e.printStackTrace();
           return new Result(false,MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
       }
   }

    @Autowired
    private ReportService reportService;

    //运营数据统计
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String,Object> map = reportService.getBusinessReportData();
        return new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }

    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        log.info("[导出运营数据报表]开始");
        Map<String, Object> reportData = reportService.getBusinessReportData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);
        String reportDate = (String) reportData.get("reportDate");
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");

        //2-读取模板构造workBook
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);
            return null;
        } catch (IOException e) {
            log.error("",e);
            return new Result(false,MessageConst.ACTION_FAIL);
        }

    }
}
